package com.gewu.pm.ui.activity.sales;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.SalesLeadBean;
import com.gewu.pm.ui.activity.filter.FilterSalesLeadActivity;
import com.gewu.pm.ui.adapter.sales.SalesLeadAdapter;
import com.gewu.pm.ui.popup.SelectTimePopup;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventCode;
import com.gewu.pm.widget.FilterBar;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BasePopupWindow;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 销售线索页面
 */
public final class SalesLeadsActivity extends AppActivity
        implements OnRefreshLoadMoreListener, BaseAdapter.OnItemClickListener,
        SalesLeadAdapter.OnConvertClickListener {

    private static final int PAGE_SIZE = 10;  // 每页10条

    // 筛选状态
    private static final int STATUS_ALL = 0;         // 全部
    private static final int STATUS_UNCONVERTED = 1; // 未转化
    private static final int STATUS_CONVERTED = 2;   // 已转化

    // UI组件
    private TextView mTotalRecordsView;
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private TextView mAddLeadButton;

    // 数据
    private SalesLeadAdapter mAdapter;
    private List<SalesLeadBean> mLeadList = new ArrayList<>();
    private int mCurrentStatus = STATUS_ALL;  // 默认全部
    private int mCurrentPage = 1;
    private FilterBar filterBar;

    public static void start(Context context) {
        Intent intent = new Intent(context, SalesLeadsActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.sales_leads_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 初始化控件
        filterBar = findViewById(R.id.filter_bar);
        mTotalRecordsView = findViewById(R.id.tv_total_records);
        mRefreshLayout = findViewById(R.id.srl_refresh);
        mRecyclerView = findViewById(R.id.rv_lead_list);
        mAddLeadButton = findViewById(R.id.btn_add_lead);


        // 设置 RecyclerView
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new SalesLeadAdapter(this);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnConvertClickListener(this);  // 设置转终端点击监听
        mRecyclerView.setAdapter(mAdapter);

        // 设置刷新
        mRefreshLayout.setOnRefreshLoadMoreListener(this);

        // 设置点击事件
        setOnClickListener(filterBar.getDateFilterLayout(), mAddLeadButton);
    }

    @Override
    protected void initData() {
        // 设置默认显示"全部"
        filterBar.setDateFilterText(getString(R.string.all_status));
        // 加载第一页数据
        loadData(1);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == filterBar.getDateFilterLayout()) {
            // 显示状态筛选弹窗
            showStatusFilterPopup();
        } else if (view == mAddLeadButton) {
            // 跳转到添加线索页面（第一页）
            SalesLeadAddActivity.start(this);
        }
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;  // 启用 EventBus
    }

    @Override
    protected void receiveEvent(EventBean event) {
        if (event.getCode() == EventCode.SALES_LEAD_ADDED) {
            // 接收新增线索完成事件，刷新列表
            mCurrentPage = 1;
            mRefreshLayout.resetNoMoreData();
            loadData(1);
            toast("新增线索成功");
        }
    }

    @Override
    public void onRightClick(View view) {
        super.onRightClick(view);
        FilterSalesLeadActivity.start(getActivity());
    }

    /**
     * 显示状态筛选弹窗
     */
    private void showStatusFilterPopup() {
        List<String> statusOptions = new ArrayList<>();
        statusOptions.add(getString(R.string.all_status));
        statusOptions.add(getString(R.string.unconverted));
        statusOptions.add(getString(R.string.converted));

        String currentText = filterBar.getDateFilterTextView().getText().toString();

        new SelectTimePopup.Builder(this)
                .setList(statusOptions)
                .setSelectedItem(currentText)
                .setListener(new SelectTimePopup.OnListener() {
                    @Override
                    public void onSelected(BasePopupWindow popupWindow, String selectedStatus) {
                        filterBar.setDateFilterText(selectedStatus);

                        // 根据选择的状态切换
                        if (selectedStatus.equals(getString(R.string.all_status))) {
                            mCurrentStatus = STATUS_ALL;
                        } else if (selectedStatus.equals(getString(R.string.unconverted))) {
                            mCurrentStatus = STATUS_UNCONVERTED;
                        } else if (selectedStatus.equals(getString(R.string.converted))) {
                            mCurrentStatus = STATUS_CONVERTED;
                        }

                        // 重新加载第一页数据
                        mCurrentPage = 1;
                        mRefreshLayout.resetNoMoreData();
                        loadData(1);
                    }
                }).showAsDropDown(filterBar.getDateFilterLayout());
    }

    /**
     * 加载数据
     */
    private void loadData(int page) {
        mCurrentPage = page;

        // 模拟数据加载
        List<SalesLeadBean> newData = generateMockData(page);

        if (page == 1) {
            // 第一页，清空数据
            mLeadList.clear();
            mLeadList.addAll(newData);
            mAdapter.setData(mLeadList);
        } else {
            // 加载更多
            mLeadList.addAll(newData);
            mAdapter.addData(newData);
        }

        // 更新记录数显示
        updateTotalRecords();

        // 完成刷新/加载更多
        if (page == 1) {
            mRefreshLayout.finishRefresh();
        } else {
            mRefreshLayout.finishLoadMore();
        }

        // 判断是否最后一页
        if (newData.size() < PAGE_SIZE) {
            mRefreshLayout.setNoMoreData(true);
        }
    }

    /**
     * 生成模拟数据
     */
    private List<SalesLeadBean> generateMockData(int page) {
        List<SalesLeadBean> data = new ArrayList<>();

        // 每页10条数据
        int start = (page - 1) * PAGE_SIZE + 1;
        int end = Math.min(page * PAGE_SIZE, 40);  // 最多40条数据

        for (int i = start; i <= end; i++) {
            SalesLeadBean bean = new SalesLeadBean();
            
            if (mCurrentStatus == STATUS_ALL) {
                // 全部状态：随机混合显示未转化和已转化
                bean.setType(i % 2);  // 偶数未转化，奇数已转化
                if (bean.isUnconverted()) {
                    bean.setName("线索名称展示在这里 " + i);
                } else {
                    bean.setName("终端名称展示在这里 " + i);
                }
            } else if (mCurrentStatus == STATUS_UNCONVERTED) {
                // 未转化
                bean.setType(0);
                bean.setName("线索名称展示在这里 " + i);
            } else {
                // 已转化
                bean.setType(1);
                bean.setName("终端名称展示在这里 " + i);
            }
            
            data.add(bean);
        }

        return data;
    }

    /**
     * 更新记录数显示
     */
    private void updateTotalRecords() {
        mTotalRecordsView.setText(String.format(getString(R.string.total_records), mLeadList.size()));
    }

    /**
     * {@link OnRefreshLoadMoreListener}
     * 下拉刷新
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mCurrentPage = 1;
        mRefreshLayout.resetNoMoreData();
        loadData(1);
    }

    /**
     * {@link OnRefreshLoadMoreListener}
     * 上拉加载更多
     */
    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        loadData(mCurrentPage + 1);
    }

    /**
     * {@link BaseAdapter.OnItemClickListener}
     * Item 点击事件
     */
    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        SalesLeadBean leadBean = mAdapter.getItem(position);
        // 跳转到详情页
        SalesLeadDetailActivity.start(this, leadBean.getName());
    }

    /**
     * {@link SalesLeadAdapter.OnConvertClickListener}
     * 转终端按钮点击事件
     */
    @Override
    public void onConvertClick(int position, SalesLeadBean leadBean) {
        // 跳转到转终端页面
        ConvertToTerminalActivity.start(this, leadBean.getName());
    }
}
